<template>
  <div class="bk_has_left_main">
    <div class="bk_card">
      <el-container style="height:100%;">
        <el-aside v-show="!isCollapse" width="280px" class="bk_aside">
          <el-container class="bk_full_wapper">
          <el-header class="bk_header" style="height:36px">
            <h5 style="display:inline">表单列表</h5>
            <div class="btn_right" style="display:inline;float:right">
              <el-button icon="el-icon-refresh" class="btn-edit" type="text" @click="refreshTree()">刷新</el-button>
              <el-button icon="el-icon-refresh" class="btn-edit" type="text" @click="addSubMangNode()">新增</el-button>
            </div>
          </el-header>
          <el-main>
          <el-tree ref="formtree" :data="formlist" node-key="root" class="formtree" lazy :load="loadNode" :props="treeprops" @node-click="handleNodeClick" @node-contextmenu="contextmenu">
            <div slot-scope="{ data }"><span :class="{'el-icon-document':data.tp=='1','el-icon-copy-document':data.tp !='1'}" />{{ data.name }}</div>
          </el-tree>
          </el-main>
          </el-container>
        </el-aside>

        <el-container class="has_left_tree">
          <div class="left_toggeler" @click="collapse"><i :class="isCollapse?'el-icon-arrow-right':'el-icon-arrow-left'" /></div>
          <el-header class="bk_header">
            <h1>{{ formname }}</h1>
            <div class="btn_right">
              <el-button v-show="showeditbtn" icon="el-icon-edit" class="btn-edit" type="text" @click="editForm">{{ editbtn_label }}</el-button>
            </div>
          </el-header>
          <el-main class="has_left">
            <form-panel
              v-show="formshow"
              ref="formpanel_perview"
              :option="curoption"
              :formkey="showformkey"
              :remote="remoteFunc"
              class="pz_sheet"
            />
            <div v-show="sheetshow" ref="sheetform" style="width:100%;height:100%" />
          </el-main>
        </el-container>

      </el-container>
    </div>
    <!-- 表单配置 -->
    <el-dialog :visible.sync="toedit" width="90%" top="5vh" class="form_dialog">
      <template slot="title">
        <div>
          【{{ curforminfo.name }}】--
          <span style="color:#ccc">表单配置</span>
        </div>
      </template>
      <div class="formaking_bk">
        <fm-making-form ref="makingForm" upload preview generate-code generate-json clearable>
          <template slot="action">
            <el-button type="text" icon="el-icon-download" @click="saveTableOptions">保存</el-button>
          </template>
        </fm-making-form>
      </div>
    </el-dialog>
    <!-- 编辑修改表单 -->
    <vxe-modal v-model="mangerformshow" :title="editWinName" resize width="80vh">
      <form-panel
        ref="managerform"
        formkey="DEV_MAIN_FORM_EDIT"
        dataUrl='saveformurl'
        :beforesave="mangerform_beforesave"
        height="300"
        :winobject="mangerformshow"
        :buttons="mangerformbuttons"
        :data="mangerformdata"
        :aftersave="managerform_aftersave"
        :remote="remoteFunc"
        @closehandler="closewin"
      >
        <template slot="cfg_selectTable">
          <el-button type="text" @click="selectTable"> 选择表</el-button>
        </template>
      </form-panel>
    </vxe-modal>
    <vxe-modal v-model="selectMainTableWinShow" width="300" height="500" title="选择主表" @show="mainTableWinShow">
      <el-container>
        <el-main style="height:370px">
          <el-tree ref="mainTableTree" node-key="root" class="formtree" lazy :load="loadMainTable" show-checkbox="true" :props="mainTableTreeprops" @node-click="">
            <div slot-scope="{ data }"><span :class="{'el-icon-document':data.tp=='1','el-icon-copy-document':data.tp !='1'}" />{{ data.name }}</div>
          </el-tree>
        </el-main>
        <el-footer>
          <div style="float:right">
            <el-button type="text" @click="sureSelectTable">确定</el-button>
            <el-button type="text" @click="selectMainTableWinShow=false">关闭</el-button>
          </div>
        </el-footer>
      </el-container>
    </vxe-modal>
    <!-- 制式表单编辑 -->
    <!-- <vxe-modal v-model="" width="80vh" height="80vh">
      <el-container>
        <el-header>
          <div style="float:right"></div>
        </el-header>
        <el-main>

        </el-main>
      </el-container>
    </vxe-modal> -->
  </div>
</template>
<script>
import Vue from 'vue'
import formpanel from '@/components/formpanel'
import VueMagicTree from '@/components/vue-magic-tree/src/components/ztree.vue'
import VueContextMenu from '@/components/vue-contextmenujs/index.js'
import request from '@/utils/requestutil.js'
import axios from 'axios'
import xspreadsheet from '@/components/x-spreadsheet/xspreadsheet.js'
import '@/components/x-spreadsheet/xspreadsheet.css'
import '../../styles/index.scss'

export default {
  components: {
    'form-panel': formpanel,
    VueMagicTree,
    'context-menu': VueContextMenu
  },
  data() {
    return {
      tableData: [],
      remoteFunc: {
        mainTableList: function(resolve, props) {
          if (this.tableData && this.tableData.length > 0) {
            resolve(this.tableData)
            return
          }
          const $t = this
         
          request({
            url: 'tablelist'
          }).then(data => {
            if (data.data) {
              $t.tableData = data.data
              if (resolve) {
                resolve(data.data)
              }
            }
          })
        //   resolve( [{
        //     key:'1dc01ad034ee4ecbbe0949727fa9e80e',
        //     value:'测试用户表'
        //   }])
        },
        jointable: function(resolve, props) {
          if (this.tableData && this.tableData.length > 0) {
            resolve(this.tableData)
            return
          }
          const $t = this
          request({
            url: 'tablelist'
          }).then(data => {
            if (data.data) {
              $t.tableData = data.data
              if (resolve) {
                resolve(data.data)
              }
            }
          })
        }
      },
      selectMainTableWinShow: false,
      editWinName: '新增表单',
      showeditbtn: false,
      defaultEmptyOption: { list: [],
        config: {
          labelWidth: 100,
          labelPosition: 'right',
          size: 'small',
          customClass: ''
        }},
      // 编辑设置
      mangerformshow: false,
      mangerformbuttons: ['save', 'reset', 'close'],
      mangerformoption: {},
      mangerformdata: {},
      isCollapse: false,
      //
      treemenudata: { axis: { x: null, y: null }, menulists: [{ btnName: '测试' }] },
      treesetting: {
        data: {
          // 设置图标库(采用iconfont class形式)
          iconMap: {
            0: 'iconjianyuede',
            1: 'icon-xuexiaodanwei',
            2: 'iconhuiyuan'
          },
          // 设置对应每个节点的节点类型，与数据中customType属性对应
          key: {
            nodeType: 'tp',
            name: 'label'
          }
        },
        view: {
          // 开启图标显示功能
          showIcon: false,
          showLine: true,
          addHoverDom: this.ontreehower
        }
      },
      treeprops: { isLeaf: this.isLeaf },
      mainTableTreeprops: { isLeaf: this.isLeaf2 },
      editbtn_label: '编辑',
      curlabel: '',
      toedit: false,
      formshow: false,
      sheetshow: false,
      showformkey: '',
      formname: '',
      curoption: {},
      formlist: [],
      curforminfo: {}
    }
  },

  mounted() {
    if (!this.$contextmenu) {
      Vue.use(VueContextMenu)
    }
    const $t = this
    // axios.get("/static/formdatalist.json").then((res) => {
    //   $t.formlist = res.data;
    // });
  },
  methods: {
    // 制式表单开始
    initSheetForm() {
      const $t = this
      setTimeout(function() {
        const option = {
          showToolbar: false,
          showGrid: true,
          height: $t.$refs.sheetform.clientHeight,
          width: $t.$refs.sheetform.clientWidth
        }
        $t.$refs.sheetform.innerHTML = ''
        $t.workbook = x_spreadsheet($t.$refs.sheetform, option)
      }, 20)
    },

    // 制式表单结束
    sureSelectTable() {
      const selectednode = this.$refs.mainTableTree.getCheckedNodes()
      if (selectednode.length > 0) {
        const node = selectednode[0]
        this.$refs.managerform.setFieldData('tableId', node.id)
        this.$refs.managerform.setFieldData('table_id', node.code)
      }
    },
    mainTableWinShow() {
    },
    selectTable() {
      this.selectMainTableWinShow = true
      console.log(32432)
    },
    isLeaf2(data, node) { return true },
    isLeaf(data, node) {
      return data.nodeType == '1'
    },
    collapse() {
      this.isCollapse = !this.isCollapse
    },
    closewin() {
      this.mangerformshow = false
    },
    refreshTree(node) {
      if (!node) { node = this.$refs.formtree.root }
      // window.ts1=this.$refs.formtree;
      const child = node.childNodes
      function removeChilds(node) {
        if (node.childNodes && node.childNodes.length > 0) {
          while (node.childNodes.length > 0) {
            removeChilds(node.childNodes[0])
            node.removeChild(node.childNodes[0])
          }
        }
      }
      removeChilds(node)

      this.loadNode(node)
    },
    loadMainTable(node, resolve) {
      request({
        url: 'tablelist'
      }).then(data => {
        if (data.data) {
          if (!resolve) {
            node.doCreateChildren.call(node, data.data)
          } else { resolve(data.data) }
        }
      })
    },
    loadNode(node, resolve) {
      let pid = node.id
      if (node.data) {
        pid = node.data.id
      }
      pid = node.level == 0 ? '' : pid
      const param = { pid: pid, level: 'SUB' }
      request({
        url: 'loadformtree',
        params: param
      }).then(data => {
        if (data.data) {
          if (!resolve) {
            node.doCreateChildren.call(node, data.data)
          } else { resolve(data.data) }
        }
      })
      // console.log(node)
    },
    // 右键菜单
    contextmenu(e, data, node) {
      this.editingnode = node
      const menuitems = [{ label: '编辑', onClick: this.editmanagerForm, values: data }, { label: '删除', onClick: this.deleteform, values: data }, '-']
      if (data.nodeType == '0') {
        menuitems.push({ label: '新增下级管理节点', onClick: this.addSubMangNode })
        menuitems.push({ label: '新增表单', onClick: this.addFormNode })
        menuitems.push('-')
        menuitems.push({ label: '新增同级管理节点', onClick: this.addNextMangNode })
        menuitems.push('-')
        const $t = this
        menuitems.push({ label: '刷新', onClick: function(muitem, data) { console.log(arguments); $t.refreshTree(muitem.values) }, values: node })
      } else if (data.nodeType == '1' ) {
        menuitems.push({ label: '新增同级管理节点', onClick: this.addNextMangNode })
        menuitems.push({ label: '新增表单', onClick: this.addFormNode })
      }
      this.$contextmenu({
        items: menuitems, event: e, data: data
      })
      return false
      // this.treemenudata.axis={x:e.x,y:e.y};
    },
    beforeAddForm(_data, formdt) {
      const $t = this
      request({
        url: 'addformurl',
        data: _data,
        method: 'post'
      }).then(data => {
        if (data.errorCode == '1' && data.formData) {
          const param = $t.bkapply({}, data.formData, formdt)
          $t.addform(param)
        }
      })
    },
    addSubMangNode(mitem, nddata) {
      this.editWinName = '新增分类'
      nddata=nddata||{id:''};
      const formdt = { pid: nddata.id, nodeType: '0' }
      const newparam = { targetId: nddata.id, level: 'SUB' }
      this.beforeAddForm(newparam, formdt)
      // this.addform(formdt)
    },
    addNextMangNode(mitem, nddata) {
      this.editWinName = '新增分类'
      const formdt = { pid: nddata.pid, nodeType: '0' }
      const newparam = { targetId: nddata.pid, level: 'NEXT' }
      this.beforeAddForm(newparam, formdt)
      // this.addform(formdt)
    },
    addFormNode(mitem, nddata) {
      this.editWinName = '新增表单'
      let pid = nddata.id
      let newparam = { targetId:pid, level: 'SUB' }
      if (nddata.nodeType == '1') {
        pid = nddata.pid
        newparam = { targetId: pid, level: 'NEXT' }
      }
      const formdt = { pid: pid, nodeType: '1' }
      this.beforeAddForm(newparam, formdt)
      // this.addform(formdt)
    },
    addform(data) {
      this.editWinName = '新增表单'
      this.mangerformdata = data
      this.mangerformshow = true
    },
    deleteform(menuitem, _data) {
      const $t = this
      request({
        url: 'deleteform',
        params: { id: _data.id }
      }).then(data => {
        if (data.errorCode == '1') {
          $t.$refs.formtree.remove(_data)
        }
        console.log(data)
      })
    },
    mangerform_beforeopen() {
      if (this.$refs.managerform) {
        const $s = this
        setTimeout(function() {
          $s.$refs.managerform.reset()
        }, 20)
      }
    },
    mangerform_beforesave(data) {
      return true
    },
    managerform_aftersave(res, data) {
      this.mangerformdata = data
      this.refreshTree(this.editingnode)
      this.editingnode = null
    },
    editmanagerForm(menuitem, data) {
     
      request({
        url:'editform',
        params:{id:data.id}
      }).then(dt=>{
        if(dt.formData){
          this.mangerformdata = dt.formData
          this.editWinName = `【${data.name}】-----编辑表单`
          this.mangerformshow = true
        }
      })
      // if(this.$refs.managerform){
      //   this.$refs.managerform.reset();
      //   this.$refs.managerform.setData(data)
      // }
      this.mangerformdata = data
      // this.mangerformoption={"tables":"bk_up_u","list":[{"type":"grid","icon":"icon-RectangleCopy","columns":[{"span":12,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"input","icon":"icon-input","options":{"width":"100%","defaultValue":"","required":true,"requiredMessage":"","dataType":"","dataTypeCheck":false,"dataTypeMessage":"","pattern":"","patternCheck":false,"patternMessage":"","placeholder":"","customClass":"","disabled":false,"labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true,"showPassword":false,"remoteFunc":"func_1598075217782","remoteOption":"option_1598075217782"},"name":"表单名称","novalid":{},"key":"1598075217782","model":"name","rules":[{"required":true,"message":"必须填写"}]}]},{"span":12,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"input","icon":"icon-input","options":{"width":"100%","defaultValue":"","required":true,"requiredMessage":"","dataType":"","dataTypeCheck":false,"dataTypeMessage":"","pattern":"","patternCheck":false,"patternMessage":"","placeholder":"","customClass":"","disabled":false,"labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true,"showPassword":false,"remoteFunc":"func_1598075217782","remoteOption":"option_1598075217782"},"name":"表单标识","novalid":{},"key":"1598075246245","model":"flag","rules":[{"required":true,"message":"必须填写"}]}]}],"options":{"gutter":0,"justify":"start","align":"top","customClass":"","hidden":false,"flex":true,"responsive":false,"remoteFunc":"func_1598075151502","remoteOption":"option_1598075151502"},"name":"栅格布局","key":"1598075151502","model":"grid_1598075151502","rules":[]},{"type":"grid","icon":"icon-RectangleCopy","columns":[{"span":12,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"select","icon":"icon-select","options":{"defaultValue":"","multiple":false,"disabled":false,"clearable":false,"placeholder":"","required":false,"requiredMessage":"","showLabel":false,"width":"","options":[{"value":"Option 1"},{"value":"Option 2"},{"value":"Option 3"}],"remote":false,"remoteType":"option","remoteOption":"option_1598257796418","filterable":false,"remoteOptions":[],"props":{"value":"value","label":"label"},"remoteFunc":"func_1598257796418","customClass":"","labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true},"name":"表单类型","novalid":{},"key":"1598257892251","model":"type","rules":[]}]},{"span":12,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"grid","icon":"icon-RectangleCopy","columns":[{"span":20,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"input","icon":"icon-input","options":{"width":"100%","defaultValue":"","required":true,"requiredMessage":"","dataType":"","dataTypeCheck":false,"dataTypeMessage":"","pattern":"","patternCheck":false,"patternMessage":"","placeholder":"","customClass":"","disabled":false,"labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true,"showPassword":false,"remoteFunc":"func_1598075217782","remoteOption":"option_1598075217782"},"name":"表单主表","novalid":{},"key":"1598075526428","model":"main_table","rules":[{"required":true,"message":"必须填写"}]}]},{"span":4,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"text","icon":"icon-wenzishezhi-","options":{"defaultValue":"选择表单","customClass":"","labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true,"remoteFunc":"func_1598075566580","remoteOption":"option_1598075566580","hideLabel":true},"name":"","novalid":{},"key":"1598075566580","model":"text_1598075566580","rules":[]}]}],"options":{"gutter":0,"justify":"start","align":"top","customClass":"","hidden":false,"flex":true,"responsive":false,"remoteFunc":"func_1598075514417","remoteOption":"option_1598075514417"},"name":"栅格布局","novalid":{},"key":"1598075514417","model":"grid_1598075514417","rules":[]}]}],"options":{"gutter":0,"justify":"start","align":"top","customClass":"","hidden":false,"flex":true,"responsive":false,"remoteFunc":"func_1598075290854","remoteOption":"option_1598075290854"},"name":"栅格布局","key":"1598075290854","model":"grid_1598075290854","rules":[]},{"type":"grid","icon":"icon-RectangleCopy","columns":[{"span":12,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[{"type":"select","icon":"icon-select","options":{"defaultValue":"","multiple":false,"disabled":false,"clearable":false,"placeholder":"","required":false,"requiredMessage":"","showLabel":false,"width":"","options":[{"value":"Option 1"},{"value":"Option 2"},{"value":"Option 3"}],"remote":false,"remoteType":"option","remoteOption":"option_1598257796418","filterable":false,"remoteOptions":[],"props":{"value":"value","label":"label"},"remoteFunc":"func_1598257796418","customClass":"","labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true},"name":"其他表","novalid":{},"key":"1598257796418","model":"tables","rules":[]}]},{"span":12,"xs":12,"sm":12,"md":12,"lg":12,"xl":12,"list":[]}],"options":{"gutter":0,"justify":"start","align":"top","customClass":"","hidden":false,"flex":true,"responsive":false,"remoteFunc":"func_1598257789648","remoteOption":"option_1598257789648"},"name":"栅格布局","key":"1598257789648","model":"grid_1598257789648","rules":[]},{"type":"textarea","icon":"icon-diy-com-textarea","options":{"width":"100%","defaultValue":"","required":false,"requiredMessage":"","disabled":false,"pattern":"","patternMessage":"","placeholder":"","customClass":"","labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true,"remoteFunc":"func_1598075834485","remoteOption":"option_1598075834485"},"name":"说明","key":"1598075834485","model":"memo","rules":[]}],"config":{"labelWidth":100,"labelPosition":"right","size":"small","customClass":"","width":"100%","ui":"element","layout":"horizontal","labelCol":3,"height":""}};
    },
    // 保存表单配置
    saveTableOptions() {
      const formoption = this.$refs.makingForm.getJSON()
      this.curoption = this.$_.cloneDeep(formoption)
      this.formlist.forEach((e) => {
        if (e.id == this.curforminfo.id) {
          e.option = JSON.stringify(this.curoption)
          return false
        }
      })
      const $t = this
      new Promise((resolve, reject) => {
        const filesd = ['input', 'textarea', 'number', 'radio', 'checkbox', 'time', 'date', 'rate', 'color', 'select', 'switch', 'slider', 'text', 'component', 'fileupload', 'imgupload', 'editor', 'cascader', 'table']
        const field = []; const blanks = []
        function getfield(options) {
          if (options.list) {
            for (let i = 0; i < options.list.length; i++) {
              getfield(options.list[i])
            }
            return
          }
          if (options.columns) {
            for (let i = 0; i < options.columns.length; i++) {
              getfield(options.columns[i])
            }
            return
          }
          if (options.tableColumns) {
            for (let i = 0; i < options.tableColumns.length; i++) {
              getfield(options.tableColumns[i])
            }
            return
          }
          if (filesd.indexOf(options.type) != -1) {
            field.push(options.model)
          }
          if (options.type == 'blank') {
            blanks.push(options.model)
          }
        }
        getfield($t.curoption)
        $t.curoption.blanks = blanks
        request({
          url: 'saveformoption', // "http://localhost:89/test/test3",//
          toVo:false,
          // url:'http://localhost:89/test/test3',
          data: { id: $t.curforminfo.id, jsonData: JSON.stringify($t.curoption), elementData: JSON.stringify(field) },
          // headers:{"Content-type":"application/x-www-form-urlencoded;charset=UTF-8'"},
          method: 'post'
        }).then(data => {
          if(data.errorCode == '1'){
            $t.$message({
              message:'保存成功',
              type:'success'
            })
          }
          resolve(data)
        })
      }).then(data => {
        console.log(data)
      })
    },
    // 左侧树点击事件
    handleNodeClick(dt, node, comp) {
      this.curoption = this.$_.cloneDeep(this.defaultEmptyOption)
      this.curFormNode = node
      if (dt.nodeType == '1' ) {
        this.showeditbtn = true
        this.curforminfo = dt
        if (dt.model == 'STANDARD') {
          this.formshow = false
          this.sheetshow = true
          this.initSheetForm()
        } else {
          this.formshow = true
          this.sheetshow = false
        }
        this.curlabel = dt.name
        this.formname = dt.name
        this.showformkey = dt.flag
        const $t = this
        if (dt.templetId) {
          this.editbtn_label = '编辑'
        } else {
          this.editbtn_label = '创建'
        }
        const table = []
        if (dt.tableId)table.push(dt.tableId)
        if (dt.joinTableId)table.push(...dt.joinTableId.split(','))
        setTimeout(function() {
          $t.curoption = $t.$refs.formpanel_perview.getOption()
          console.log($t.curoption)
        }, 20)
        // if (dt.jsonData) {
        //   let option =
        //     typeof dt.jsonData == "string" ? JSON.parse(dt.jsonData) : dt.jsonData;
        //   this.curoption = option;
        //   this.editbtn_label = "编辑";
        // } else {
        //   this.editbtn_label = "创建";
        // }
      } else {
        this.showeditbtn = false
        this.formname = ''
        this.formshow = false
      }
    },
    // 表单编辑
    editForm() {
      const s = this.$refs['formpanel_perview'].getData()
      this.toedit = true
      const $t = this
      const dt = this.curFormNode.data
      const table = []
      if (dt.tableId)table.push(dt.tableId)
      if (dt.joinTableId)table.push(...dt.joinTableId.split(','))
      const flag = dt.flag
      setTimeout(function() {
        const option = $t.$refs.formpanel_perview.getOption() || $t.curoption
        option.tables = table.join(',')
        option.flag = flag
        if (option) {
          $t.$refs.makingForm.setJSON($t.$_.cloneDeep(option))
        } else {
          $t.$refs.makingForm.clear()
        }
      }, 20)
    }
  }
}
</script>
